import {Action} from 'redux';

import immutableObject from '../common/immutableObject';
import {ActionType} from './ActionType';
import {IDesign} from '../types/IDesign';

export interface ActiveDesignState {
  [active: string]: string;
}

export interface ActiveDesignAction extends Action {
  type: ActionType;
  designId?: string;
  design?: IDesign;
}

function activeDesignReducer(state: ActiveDesignState = {}, action: ActiveDesignAction): ActiveDesignState {
  switch (action.type) {
    case ActionType.ACTIVE_DESIGN:
      return _activeDesign(state, action.designId);

    case ActionType.ADD_DESIGN:
      // 添加(打开)新的设计时, 直接使新打开的设计变为当前选中的设计
      return _activeDesign(state, action.design.id);

    case ActionType.REMOVE_DESIGN:
      return _removeDesign(state, action.designId);

    default:
      return state;
  }
}

function _activeDesign(state: ActiveDesignState, designId: string): ActiveDesignState {
  return immutableObject.set(state, 'active', designId);
}

function _removeDesign(state: ActiveDesignState, designId: string): ActiveDesignState {
  if (state.active !== designId) {
    return state;
  }
  return immutableObject.set(state, 'active', '');
}

export default activeDesignReducer;
